using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Server.Entities.SystemTextJson;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Server.Application
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            //    .AddJsonOptions(options =>
            //{
            //    //配置时间序列化格式
            //    options.JsonSerializerOptions.Converters.Add(new DateTimeOffsetConverter());
            //}).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
            services.AddHttpContextAccessor();
            services.Configure<KestrelServerOptions>(x => x.AllowSynchronousIO = true)
                .Configure<IISServerOptions>(x => x.AllowSynchronousIO = true);
            var jwtConfig = new Server.Utils.ConfigurationUtil().GetAppSettings<Server.Entities.Appsettings.JwtConfig>("JWT");
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(x =>
                {
                    x.RequireHttpsMetadata = false;

                    x.SaveToken = true;

                    x.TokenValidationParameters = new TokenValidationParameters()
                    {
                        LifetimeValidator = (notBefore, expires, securityToken, validationParameters) =>
                        {
                            bool t = DateTime.UtcNow < expires;
                            return t;
                        },

                        ValidateLifetime = true,
                        ValidateAudience = false,
                        ValidateIssuer = true,
                        ValidIssuer = jwtConfig.Issuer,
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.Key)),
                    };
                    x.Events = new JwtBearerEvents
                    {
                        OnChallenge = context =>
                        {
                            Utils.LogUtil.LogWarning(Utils.LogUtil.BuildRequetLog(context.Request,"登录失效"));
                            //string contentFromBody;
                            //using (var reader = new StreamReader(context.Request.Body))
                            //{
                            //    contentFromBody = reader.ReadToEnd();
                            //}
                            //Utils.LogUtil.LogWarning(context.Request.Path, "登录失效：params：" + context.Request.QueryString + ",Body：" + contentFromBody+",token："+(context.Request.Headers["token"].ToString()??"")+",platform："+ (context.Request.Headers["token"].ToString()));
                            return Task.FromResult(0);
                        },
                        OnMessageReceived = context =>
                        {
                            var authorizationIsHave = context.Request.Headers.TryGetValue("Authorization", out _);
                            if (authorizationIsHave)
                            {
                                return Task.CompletedTask;
                            }
                            var authorization2IsHave = context.Request.Headers.TryGetValue("token", out var token);
                            if (authorization2IsHave)
                            {
                                context.Request.Headers.Add("Authorization", token);
                            }
                            return Task.CompletedTask;
                        }
                    };
                });
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "Server.Application", Version = "v1" });
#if DEBUG
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath = System.IO.Path.Combine(basePath, "Server.Application.xml");
                var _xmlPath = System.IO.Path.Combine(basePath, "Server.Entities.xml");
                c.IncludeXmlComments(_xmlPath);
                c.IncludeXmlComments(xmlPath);
                c.OperationFilter<AuthResponsesOperationFilter>();
#endif
            });
            services.AddLoggingFileUI();
            services.AddMvc(option =>
            {
                option.EnableEndpointRouting = false;
                option.Filters.Add(typeof(ResourceFilter));
            }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Server.Application v1"));
            }
            HttpContextUtil.Configure(app.ApplicationServices.GetRequiredService<Microsoft.AspNetCore.Http.IHttpContextAccessor>());
            app.UseMiddleware(typeof(Api.Code.ExceptionHandlerMiddleWare));
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseStaticFiles();
            app.UseMvc(x =>
            {
                //    //x.EnableEndpointRouting = false;
            });

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
